﻿namespace PlugNT.Database.Common.Complex
{
    using PlugNT.Database.Common;
    using PlugNT.Safe;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Runtime.InteropServices;

    public abstract class DbHelper
    {
        protected DbHelper()
        {
        }

        private static DbCommand BuildIntCommand(DbInfo dbinfo, DbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            DbCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(DbProvider.MakeIntParam(dbinfo, "ReturnValue"));
            return command;
        }

        private static DbCommand BuildQueryCommand(DbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            DbCommand command = connection.CreateCommand();
            command.CommandText = storedProcName;
            command.CommandType = CommandType.StoredProcedure;
            foreach (DbParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }
            return command;
        }

        public static bool ColumnExists(DbInfo dbinfo, string tableName, string columnName)
        {
            string sQLString = "select count(1) from syscolumns where [id]=object_id('" + StringHelper.SqlFilter(tableName) + "') and [name]='" + StringHelper.SqlFilter(columnName) + "'";
            object single = GetSingle(dbinfo, sQLString);
            if (single == null)
            {
                return false;
            }
            return (Convert.ToInt32(single) > 0);
        }

        public static DbDataReader ExecuteReader(DbInfo dbinfo, string SQLString)
        {
            DbDataReader reader2;
            DbConnection connection = DbProvider.CreateConnection(dbinfo);
            DbCommand command = connection.CreateCommand();
            try
            {
                command.Connection = connection;
                command.CommandText = SQLString;
                connection.Open();
                reader2 = command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (DbException exception)
            {
                throw exception;
            }
            return reader2;
        }

        public static DbDataReader ExecuteReader(DbInfo dbinfo, string SQLString, params DbParameter[] cmdParms)
        {
            DbDataReader reader2;
            DbConnection conn = DbProvider.CreateConnection(dbinfo);
            DbCommand cmd = conn.CreateCommand();
            try
            {
                PrepareCommand(cmd, conn, null, SQLString, cmdParms);
                DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                reader2 = reader;
            }
            catch (DbException exception)
            {
                throw exception;
            }
            return reader2;
        }

        public static int ExecuteSql(DbInfo dbinfo, string SQLString)
        {
            int num2;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand command = connection.CreateCommand();
                try
                {
                    command.Connection = connection;
                    command.CommandText = SQLString;
                    connection.Open();
                    return command.ExecuteNonQuery();
                }
                catch (DbException exception)
                {
                    connection.Close();
                    throw exception;
                }
                finally
                {
                    if (command != null)
                    {
                        command.Dispose();
                    }
                }
            }
            return num2;
        }

        public static int ExecuteSql(DbInfo dbinfo, string SQLString, params DbParameter[] cmdParms)
        {
            int num2;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                using (DbCommand command = connection.CreateCommand())
                {
                    try
                    {
                        PrepareCommand(command, connection, null, SQLString, cmdParms);
                        int num = command.ExecuteNonQuery();
                        command.Parameters.Clear();
                        return num;
                    }
                    catch (DbException exception)
                    {
                        throw exception;
                    }
                    finally
                    {
                        if ((connection != null) && (connection.State == ConnectionState.Open))
                        {
                            connection.Close();
                        }
                    }
                }
            }
            return num2;
        }

        public static int ExecuteSqlByTime(DbInfo dbinfo, string SQLString, int Times)
        {
            int num2;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand command = connection.CreateCommand();
                try
                {
                    command.Connection = connection;
                    command.CommandText = SQLString;
                    connection.Open();
                    command.CommandTimeout = Times;
                    return command.ExecuteNonQuery();
                }
                catch (DbException exception)
                {
                    connection.Close();
                    throw exception;
                }
                finally
                {
                    if (command != null)
                    {
                        command.Dispose();
                    }
                }
            }
            return num2;
        }

        public static int ExecuteSqlTran(DbInfo dbinfo, List<string> SQLStringList, out string error)
        {
            int num3;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand command = connection.CreateCommand();
                command.Connection = connection;
                connection.Open();
                DbTransaction transaction = connection.BeginTransaction();
                command.Transaction = transaction;
                try
                {
                    int num = 0;
                    for (int i = 0; i < SQLStringList.Count; i++)
                    {
                        string str = SQLStringList[i];
                        if (str.Trim().Length > 1)
                        {
                            command.CommandText = str;
                            num += command.ExecuteNonQuery();
                        }
                    }
                    transaction.Commit();
                    error = "";
                    num3 = num;
                }
                catch (Exception exception)
                {
                    transaction.Rollback();
                    error = exception.Message + "\n" + exception.StackTrace;
                    num3 = 0;
                }
            }
            return num3;
        }

        public static bool Exists(DbInfo dbinfo, string strSql)
        {
            int num;
            object single = GetSingle(dbinfo, strSql);
            if (object.Equals(single, null) || object.Equals(single, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(single.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public static bool Exists(DbInfo dbinfo, string strSql, params DbParameter[] cmdParms)
        {
            int num;
            object objA = GetSingle(dbinfo, strSql, cmdParms);
            if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(objA.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public static int GetMaxID(DbInfo dbinfo, string FieldName, string TableName)
        {
            string sQLString = "select max(" + StringHelper.SqlFilter(FieldName) + ") from " + StringHelper.SqlFilter(TableName);
            object single = GetSingle(dbinfo, sQLString);
            if (single == null)
            {
                return 1;
            }
            return int.Parse(single.ToString());
        }

        public static object GetSingle(DbInfo dbinfo, string SQLString)
        {
            object obj3;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand command = connection.CreateCommand();
                try
                {
                    command.Connection = connection;
                    command.CommandText = SQLString;
                    connection.Open();
                    object objA = command.ExecuteScalar();
                    if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
                    {
                        return null;
                    }
                    return objA;
                }
                catch (DbException exception)
                {
                    connection.Close();
                    throw exception;
                }
                finally
                {
                    if (command != null)
                    {
                        command.Dispose();
                    }
                }
            }
            return obj3;
        }

        public static object GetSingle(DbInfo dbinfo, string SQLString, params DbParameter[] cmdParms)
        {
            object obj3;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand cmd = connection.CreateCommand();
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    object objA = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
                    {
                        return null;
                    }
                    return objA;
                }
                catch (DbException exception)
                {
                    throw exception;
                }
                finally
                {
                    if (cmd != null)
                    {
                        cmd.Dispose();
                    }
                }
            }
            return obj3;
        }

        public static string Help()
        {
            return "mailto:549002835@qq.com";
        }

        private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (DbParameter parameter in cmdParms)
                {
                    if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        public static DataSet Query(DbInfo dbinfo, string SQLString)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DataSet dataSet = new DataSet();
                try
                {
                    connection.Open();
                    DbDataAdapter adapter = DbProvider.GetFactory(dbinfo).CreateDataAdapter();
                    DbCommand command = connection.CreateCommand();
                    command.CommandText = SQLString;
                    adapter.SelectCommand = command;
                    adapter.Fill(dataSet);
                }
                catch (DbException exception)
                {
                    throw new Exception(exception.Message);
                }
                return dataSet;
            }
        }

        public static DataSet Query(DbInfo dbinfo, string SQLString, params DbParameter[] cmdParms)
        {
            DataSet set2;
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand cmd = connection.CreateCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (DbDataAdapter adapter = DbProvider.GetFactory(dbinfo).CreateDataAdapter())
                {
                    adapter.SelectCommand = cmd;
                    DataSet dataSet = new DataSet();
                    try
                    {
                        adapter.Fill(dataSet, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (DbException exception)
                    {
                        throw new Exception(exception.Message);
                    }
                    set2 = dataSet;
                }
            }
            return set2;
        }

        public static bool ReSetTable(DbInfo dbinfo, string tabName, string idName)
        {
            ExecuteSql(dbinfo, "delete from " + StringHelper.SqlFilter(tabName));
            return (ExecuteSql(dbinfo, Tables.GetReSetTableStr(dbinfo, tabName, idName)) > 0);
        }

        public static DbDataReader RunProcedure(DbInfo dbinfo, string storedProcName, IDataParameter[] parameters)
        {
            DbConnection connection = DbProvider.CreateConnection(dbinfo);
            connection.Open();
            DbCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
            connection.Close();
            return reader;
        }

        public static int RunProcedure(DbInfo dbinfo, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                connection.Open();
                DbCommand command = BuildIntCommand(dbinfo, connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                int num = (int) command.Parameters["ReturnValue"].Value;
                connection.Close();
                return num;
            }
        }

        public static DataSet RunProcedure(DbInfo dbinfo, string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                DbDataAdapter adapter = DbProvider.GetFactory(dbinfo).CreateDataAdapter();
                adapter.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                adapter.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }

        public static DataSet RunProcedure(DbInfo dbinfo, string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                DbDataAdapter adapter = DbProvider.GetFactory(dbinfo).CreateDataAdapter();
                adapter.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                adapter.SelectCommand.CommandTimeout = Times;
                adapter.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }

        public static bool TabExists(DbInfo dbinfo, string TableName)
        {
            int num;
            string searchTableSql = DbProvider.GetSearchTableSql(dbinfo, TableName);
            object objA = null;
            try
            {
                objA = GetSingle(dbinfo, searchTableSql);
            }
            catch
            {
                objA = null;
            }
            if (object.Equals(objA, null) || object.Equals(objA, DBNull.Value))
            {
                num = 0;
            }
            else
            {
                num = int.Parse(objA.ToString());
            }
            if (num == 0)
            {
                return false;
            }
            return true;
        }

        public static DataTable TabQuery(DbInfo dbinfo, string SQLString)
        {
            return Query(dbinfo, SQLString).Tables[0];
        }
    }
}

